package MysqlDB

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var MysqlDB *gorm.DB

// 控制台打印sql语句日志
var newLogger = logger.New(
	log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
	logger.Config{
		SlowThreshold:             time.Second, // Slow SQL threshold
		LogLevel:                  logger.Info, // Log level
		IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
		ParameterizedQueries:      true,        // Don't include params in the SQL log
		Colorful:                  true,        // Disable color
	},
)

func init() {
	dbuser := fmt.Sprintf("%v", viper.Get("mysql.user"))
	dbpwd := fmt.Sprintf("%v", viper.Get("mysql.pwd"))
	dbserver := fmt.Sprintf("%v", viper.Get("mysql.server"))
	dbname := fmt.Sprintf("%v", viper.Get("mysql.name"))
	dbport := fmt.Sprintf("%v", viper.Get("mysql.port"))
	var err error
	MysqlDB, err = gorm.Open(mysql.Open(dbuser+":"+dbpwd+"@tcp("+dbserver+":"+dbport+")/"+
		dbname+"?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{Logger: newLogger})
	if err != nil {
		logrus.Panic("数据连接失败···")

	}
	logrus.Info("数据库连接成功")

}
